__author__ = 'haozes'
from string import Template
import csv
import os
import shutil
import re
import json
from functools import reduce
import subprocess
from datetime import datetime

# 在EXCEL中第1题是从第8列开始，索引从0开始所以+6
START_COL = 6

gUserScore = {}


def addScore(grade, name, studyNo, score):
    key = grade + name + studyNo
    if key in gUserScore:
        gUserScore[key] = gUserScore[key] + score
    else:
        gUserScore[key] = score


def addStdScore(grade, name, studyNo,score):
    key = 'std' + grade + name+ studyNo
    if key in gUserScore:
        gUserScore[key] = gUserScore[key] + score
    else:
        gUserScore[key] = score


def getScore(grade, name,studyNo):
    key = grade + name + studyNo
    if key in gUserScore:
        return gUserScore[key]
    else:
        return 0


def getStdScore(grade, name,studyNo):
    key = 'std' + grade + name + studyNo
    if key in gUserScore:
        return gUserScore[key]
    else:
        return 0


def rsum(arr):
    ret = 0
    if type(arr) == list:
        ret = sum(map(lambda x: float(x.strip()) if isinstance(x, str) else float(x), arr))
    else:
        ret = float(arr)
    if int(ret) - ret == 0:
        return int(ret)
    else:
        return ret


def ft(value):
    return format(value, '0.1%')


def genSubject(config):
    print('-----------process {0}'.format(config['file']))
    if (len(config['column']) != len(config['score'])):
        print('error:模版列和分数列数目不相等！！')
        return
    rows = readRows(config['file'])
    xuke = config['sub']
    # 前缀
    prefix = config['prefix']
    p1 = prefix[0]
    p2 = prefix[1]

    for row in rows:
        #满分
        total = 0
        name = row[1].strip()
        grade = row[5].strip()
        # 准考证号
        studyNo = row[3].strip()

        tpl = getReportFileContent(name, grade,studyNo)

        d = dict(name=name, grade=grade)
        #我的得分
        myTotal = 0
        for idx in range(len(config['column'])):
            col = config['column'][idx]
            score = config['score'][idx]
            ignore = "i" in col
            myScore = 0
            seg = col['seg']

            key1 = p1 + str(idx + 1).zfill(2)
            key2 = p2 + str(idx + 1).zfill(2)
            if (len(seg) == 2):
                myScore = d[key1] = rsum(row[seg[0] + START_COL:seg[1] + START_COL + 1])
                d[key2] = ft(myScore / score)
            else:
                myScore = d[key1] = rsum(row[seg[0] + START_COL])
                d[key2] = ft(myScore / score)

            if not ignore:
                total += score
                myTotal += myScore
                #print(myScore)

        d[xuke] = myTotal
        d[xuke + '_0'] = ft((myTotal / total))

        addScore(grade, name,studyNo, d[xuke])
        addStdScore(grade, name,studyNo, total)

        stdScore = getStdScore(grade, name,studyNo)
        score = getScore(grade, name,studyNo)
        #说明是最后一科了
        if stdScore >= gUserScore['total']:
            d['total'] = score
            d['total_0'] = ft(score / gUserScore['total'])

        html = Template(tpl).safe_substitute(d)
        saveUserReportFile(name, grade, studyNo, html)

        print('process :{0}-{1}-{2} success'.format(grade, name,studyNo))


def replaceUnused(str):
    regex = r"\$[a-z]([a-z]+|(\d+)|(_))+"
    subst = "-"
    return re.sub(regex, subst, str, 0)


def processUnusedLable():
    outputDir = os.path.join(os.getcwd(), 'output')
    htmlFiles = [f for f in os.listdir(outputDir)]
    for htmlFile in htmlFiles:
        p = os.path.join(outputDir, htmlFile)
        html = open(p, 'r', encoding='utf-8').read()
        f = open(p, 'w', encoding='utf-8')
        html = replaceUnused(html)
        f.write(html)
        f.close()
        print('clear :{0}'.format(htmlFile))


def readRows(filename):
    p = os.path.join(os.getcwd(), filename)
    reader = csv.reader(open(p, 'r', encoding='utf-8'), delimiter=',')
    rows = enumerate(reader)
    result = []
    for i, row in rows:
        if (i > 1):
            result.append(row)
    return result


def readTemplate():
    return open('template.htm', 'r', encoding='utf-8').read()


def getReportFileName(name, grade, studyNo):
    return grade + '_' + name + '_' + studyNo + '.html'


def getReportFilePath(name, grade, studyNo):
    filename = getReportFileName(name, grade,studyNo)
    p = os.path.join('output', filename)
    return p


def getReportFileContent(name, grade, studyNo):
    p = getReportFilePath(name, grade, studyNo)
    if os.path.exists(p) == False:
        tpl = readTemplate()
        f = open(p, 'w', encoding='utf-8')
        f.write(tpl)
        f.close()
    return open(p, 'r', encoding='utf-8').read()


def saveUserReportFile(name, grade, studyNo, html):
    p = getReportFilePath(name, grade,studyNo)
    file = open(p, 'w', encoding='utf-8')
    file.write(html)
    file.close()


def clearOutputDir():
    p = os.path.join(os.getcwd(), 'output')
    if os.path.exists(p):
        shutil.rmtree(p, ignore_errors=True)

    os.makedirs(p)


def unzipXls(xlsfile):
    os.system('python xlsx2csv.py  -a "{0}" ./'.format(xlsfile))


def main():
    clearOutputDir()
    #TODO:先注释掉调试
    xlsdata = os.path.join(os.getcwd(), 'data.xlsx')
    unzipXls(xlsdata)

    str = open('config.json', 'r', encoding='utf-8').read()
    config = json.loads(str)
    print(config)
    gUserScore['total'] = 0
    for cfg in config:
        for idx in range(len(cfg['column'])):
            s = cfg['column'][idx]
            if "i" not in s:
                gUserScore['total'] += cfg['score'][idx]
    print("total:{0}".format(gUserScore['total']))

    for cfg in config:
        genSubject(cfg)

    processUnusedLable()

    print('All finsish!!')


main()
